<template>
    <div class="personalClueDataStyle">
      <!-- 搜索条件 -->
      <div class="formStyle">
        <RadioGroup v-model="formInline.time" type="button" @on-change="timeFun">
          <Radio label="今天"></Radio>
          <Radio label="昨日"></Radio>
          <Radio label="最近7天"></Radio>
          <Radio label="本周"></Radio>
          <Radio label="上周"></Radio>
          <Radio label="本月"></Radio>
        </RadioGroup>
        <span class="spanMarginRL">日期选择：</span><DatePicker type="daterange" placement="bottom-end" v-model="formInline.date" placeholder="请选择日期范围" style="width: 220px" @on-change="dateFun"></DatePicker>
      </div>
      <div class="formStyle">
        <span class="spanMargin">地区：</span>
        <Select v-model="formInline.province" style="width:150px;" placeholder="请选择省份" filterable @on-select="selectProvince">
          <Option v-for="item in provinceList" :value="item.cityCode" :key="item.cityCode" :label="item.cityName"></Option>
        </Select>
        <Select v-model="formInline.city" style="width:150px; margin: 0 10px;" placeholder="请选择市" filterable @on-select="selectCity" >
          <Option v-for="item in cityList" :value="item.cityCode" :key="item.cityCode" :label="item.cityName"></Option>
        </Select>
        <Select v-model="formInline.county" @on-select="countyFun" style="width:150px;" placeholder="请选择区/县" filterable >
          <Option v-for="item in countyList" :value="item.cityCode" :key="item.cityCode" :label="item.cityName"></Option>
        </Select>
        <span class="spanMarginRL">楼盘：</span>
        <Select
          :disabled="(formInline.province&&formInline.city&&formInline.county) ? false : true"
          v-model="formInline.realEstate"
          filterable
          placeholder="请搜索选择楼盘"
          style="width:200px;"
        >
          <Option v-for="(option, index) in realEstateList" :value="option.buildingId" :key="option.buildingId">{{option.buildingAlias}}</Option>
        </Select>
      </div>
      <div class="formStyle">
        <Row>
          <Col offset="12">
            <Button type="primary" style=" width: 80px;" @click="queryFun">查 询</Button>
            <Button style=" width: 80px; margin: 0 10px;" @click="emptyFun">重 置</Button>
            <Button type="primary" style=" width: 80px;" :disabled="data1.length > 0 ? false : true" @click="exportFun">导 出</Button>
          </Col>
        </Row>
      </div>
      <!-- table -->
      <Table :loading="loading" ref="TableHeight" :max-height="onresizeHeight" :columns="columns1" :data="data1" @on-sort-change="sortTableFun">
        <template slot-scope="{ row }" slot="propertiesSale">
          <p>{{ row.buildingAlias || '-' }}</p>
          <p>{{ (row.cityName || '') + (row.cityName  ? ' | ' : '') + (row.areaName || '')}}</p>
        </template>
      </Table>
      <!-- 分页 -->
      <div class="pagePublicStyle" v-show="pageData.total > 0">
        <div class="totalCount">
          当前第 {{pageData.page}} 页，
          当前第 {{(pageData.page-1)*pageData.rows+1}} 条到第 {{pageData.page*pageData.rows>pageData.total?pageData.total:pageData.page*pageData.rows}} 条，
          共 {{pageData.total}} 条
        </div>
        <Page class="pager" :total="pageData.total" :pageSize="pageData.rows" :current="pageData.page" :page-size-opts="pageData.pageSizeOpts" @on-change="pageOnChangeFun" @on-page-size-change="pageOnPageSizeChangeFun" placement="top" show-elevator show-sizer />
      </div>
    </div>
</template>
<script>
  import { cityPage, buildingReport, userbuildinglist, userBuildingArea } from "@/api/dataManagement.js";
  import Helper from "@/common/helper.js";
  import {buildExport} from "@/common/axios"
  import tool from "@/common/tool"
  let userMess = JSON.parse(tool.getStorage('userMess'))
  export default {
    components: {

    },
    data() {
        return {
          buildingIds: [],
          loading: false,
          onresizeHeight: 0,
          pageData: {
            total: 0,
            page: 1,
            rows: 14,
            pageSizeOpts: [20, 30, 40, 50]
          },
          formInline: {
            time: '今天',
            date: '',
            province: '',
            provinceName: '',
            city: '',
            county: '',
            realEstate: ''
          },
          provinceList: [],
          cityList: [],
          countyList: [],
          realEstateList: [],
          sortOBj: '',
          columns1: [
            {
              title: '序号',
              type: 'index',
              width: 80,
              align: 'center'
            },
            {
              title: '楼盘名称',
              key: 'buildingAlias',
              minWidth: 220,
              slot: 'propertiesSale'
            },
            {
              title: '互动',
              key: 'interact',
              minWidth: 100,
              sortable: 'custom',
              render: (h, params) => {
                return h('div',  params.row.interact || '-');
              }
            },
            {
              title: '留资',
              key: 'retain',
              minWidth: 100,
              sortable: 'custom',
              render: (h, params) => {
                return h('div',  params.row.retain || '-');
              }
            },
            {
              title: '到访',
              key: 'follow_views',
              minWidth: 100,
              sortable: 'custom',
              render: (h, params) => {
                return h('div',  params.row.followViews || '-');
              }
            },
            {
              title: '认购',
              key: 'subscription',
              minWidth: 100,
              render: (h, params) => {
                return h('div',  params.row.subscription || '-');
              }
            },
            {
              title: '签约',
              key: 'SIGN',
              minWidth: 100,
              render: (h, params) => {
                return h('div',  params.row.sign || '-');
              }
            },
            {
              title: '互动留资率',
              key: 'interactRetainRate',
              minWidth: 120,
              sortable: 'custom',
              render: (h, params) => {
                return h('div',  (params.row.interactRetainRate&&params.row.interactRetainRate +'%') || '-');
              }
            },
            {
              title: '留资到访率',
              key: 'interactFollowViewsRate',
              minWidth: 120,
              sortable: 'custom',
              render: (h, params) => {
                return h('div',  (params.row.interactFollowViewsRate&&params.row.interactFollowViewsRate +'%') || '-');
              }
            },
            {
              title: '到访认购率',
              key: 'followViewsSubscriptionRate',
              minWidth: 120,
              sortable: 'custom',
              render: (h, params) => {
                return h('div', (params.row.followViewsSubscriptionRate&&params.row.followViewsSubscriptionRate +'%') || '-');
              }
            },
            {
              title: '认购签约率',
              key: 'subscriptionSignRate',
              minWidth: 120,
              sortable: 'custom',
              render: (h, params) => {
                return h('div', (params.row.subscriptionSignRate&&params.row.subscriptionSignRate +'%') || '-');
              }
            }
          ],
          data1: []
        }
    },
    methods: {
      // 楼盘名称 模糊搜索
      countyFun (quer) {
        let that = this;
        let params = {
            page: 1,
            rows: 100,
            buildingAlias: '',
            provinceCode: that.formInline.province,
            cityCode: that.formInline.city,
            areaCode: quer.value
          }
          userBuildingArea(params).then((res) => {
            if (res) {
              that.realEstateList = res.list;
            } else {
              that.realEstateList = [];
            }
          }).catch(err=>{
            this.$Message.error(err)
          })
      },
      dateFun() {
        this.formInline.time = ''
      },
      queryFun() {
        this.pageData.page = 1;
        // this.pageData.rows = 14;
        this.initData();
      },
      emptyFun() {
        this.formInline.time = '昨日'
        let timer = this.timeForMat(1)
        this.formInline.date = [timer.t2, timer.t1]
        this.formInline.province = ''
        this.formInline.provinceName = ''
        this.formInline.city = ''
        this.formInline.county = ''
        this.formInline.realEstate = ''
        this.realEstateList = []
        this.cityPageList(2)
        this.pageData.page = 1;
        this.sortOBj = ''
        // this.pageData.rows = 14;
        this.initData();
      },
      exportFun() {
        let params = {
          startTime: (this.formInline.date[0] && Helper.timestampToTime(this.formInline.date[0], 'date')) || '',
          endTime: (this.formInline.date[1] && Helper.timestampToTime(this.formInline.date[1], 'date')) || '',
          buildingId: this.formInline.realEstate,
          buildingIds: this.buildingIds,
          sort: (this.sortOBj && this.sortOBj.order == 'normal' ? 'interact' : this.sortOBj.key) || 'interact',
          rule: (this.sortOBj && this.sortOBj.order == 'normal' ? 'desc' : this.sortOBj.order) || 'desc',
          provinceName: this.formInline.provinceName,
          createExcelType: 2,
          userId: userMess.appId
        }
        buildExport("楼盘线索数据", '/dt-business/dataReport/down', params);
      },
      initData() {
        let params = {
          page: this.pageData.page,
          rows: this.pageData.rows,
          startTime: (this.formInline.date[0] && Helper.timestampToTime(this.formInline.date[0], 'date')) || '',
          endTime: (this.formInline.date[1] && Helper.timestampToTime(this.formInline.date[1], 'date')) || '',
          buildingId: this.formInline.realEstate,
          buildingIds: this.buildingIds,
          provinceName: this.formInline.provinceName,
          sort: (this.sortOBj && this.sortOBj.order == 'normal' ? 'interact' : this.sortOBj.key) || 'interact',
          rule: (this.sortOBj && this.sortOBj.order == 'normal' ? 'desc' : this.sortOBj.order) || 'desc'
        }
        buildingReport(params).then(res=>{
          this.loading = false
          if (res && res.list) {
            this.data1 = res.list
            this.pageData.total = Number(res.total)
            this.$nextTick(() => {
              this.onresizeHeight = window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 100
            });
          } else {
            this.pageData.total = 0
            this.data1 = []
          }
        }).catch(err=>{
          this.loading = false
          this.$Message.error(err)
        })
      },
      // 分页 页码改变事件
      pageOnChangeFun(page) {
        this.pageData.page = page;
        this.initData();
      },
      // 分页 每页条数改变事件
      pageOnPageSizeChangeFun(rows) {
        this.pageData.rows = rows;
        this.pageData.page = 1;
        this.initData();
      },
      sortTableFun(parm) {
        this.sortOBj = parm
        this.pageData.page = 1;
        // this.pageData.rows = 14;
        this.initData();
      },
      // 选择省
      selectProvince(params) {
        this.formInline.provinceName = params.label
        this.cityPageList(3, params.value)
      },
      // 选择市
      selectCity(params) {
        this.cityPageList(4, params.value)
      },
      timeForMat (count) {
         let time1 = new Date()
         time1.setTime(time1.getTime() - (24 * 60 * 60 * 1000))
         let Y1 = time1.getFullYear()
         let M1 = ((time1.getMonth() + 1) >= 10 ? (time1.getMonth() + 1) : '0' + (time1.getMonth() + 1))
         let D1 = (time1.getDate() >= 10 ? time1.getDate() : '0' + time1.getDate())
         let timer1 = Y1 + '-' + M1 + '-' + D1
         let time2 = new Date()
         time2.setTime(time2.getTime() - (24 * 60 * 60 * 1000 * count))
         let Y2 = time2.getFullYear()
         let M2 = ((time2.getMonth() + 1) >= 10 ? (time2.getMonth() + 1) : '0' + (time2.getMonth() + 1))
         let D2 = (time2.getDate() >= 10 ? time2.getDate() : '0' + time2.getDate())
         let timer2 = Y2 + '-' + M2 + '-' + D2
         return {
             t1: timer1,
             t2: timer2
         }
      },
      formatDate(date) {
        let myyear = date.getFullYear();
        let mymonth = date.getMonth() + 1;
        let myweekday = date.getDate();
        if (mymonth < 10) {
          mymonth = "0" + mymonth;
        }
        if (myweekday < 10) {
          myweekday = "0" + myweekday;
        }
        return (myyear + "-" + mymonth + "-" + myweekday);
      },
      getMonthDays(myMonth) {
        let now = new Date();
        let nowYear = now.getYear();
        nowYear += (nowYear < 2000) ? 1900 : 0;
        let monthStartDate = new Date(nowYear, myMonth, 1);
        let monthEndDate = new Date(nowYear, myMonth + 1, 1);
        let days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
        return days;
      },
      timeFun(val) {
        let now = new Date();
        let nowDayOfWeek = now.getDay() == 0 ? 7 : now.getDay();
        let nowDay = now.getDate();
        let nowMonth = now.getMonth();
        let nowYear = now.getYear();
        nowYear += (nowYear < 2000) ? 1900 : 0;
        if (val === '今天') {
          let timer = this.timeForMat('')
          this.formInline.date = [timer.t2, timer.t2]
        } else if (val === '昨日') {
          let timer = this.timeForMat(1)
          this.formInline.date = [timer.t2, timer.t1]
        } else if (val === '最近7天') {
          let timer = this.timeForMat(7)
          this.formInline.date = [timer.t2, timer.t1]
        } else if (val === '本周') {
          let weekStartDate = this.formatDate(new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1));
          let weekEndDate = this.formatDate(new Date(nowYear, nowMonth, nowDay + (7 - nowDayOfWeek)));
          this.formInline.date = [weekStartDate, weekEndDate]
        } else if (val === '上周') {
          let weekStartDate = this.formatDate(new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 6));
          let weekEndDate = this.formatDate(new Date(nowYear, nowMonth, nowDay - nowDayOfWeek));
          this.formInline.date = [weekStartDate, weekEndDate]
        } else if (val === '本月') {
          let monthStartDate = this.formatDate(new Date(nowYear, nowMonth, 1));
          let monthEndDate = this.formatDate(new Date(nowYear, nowMonth, this.getMonthDays(nowMonth)));
          this.formInline.date = [monthStartDate, monthEndDate]
        }
      },
      cityPageList(level = 2, parentCode = '') {
        let parms = {
          level,
          parentCode
        }
        cityPage(parms).then(res =>{
          this.formInline.realEstate = ''
          switch (level) {
            case 2:
              this.formInline.city = ''
              this.formInline.county = ''
              this.cityList = []
              this.countyList = []
              this.provinceList = res.list
              break;
            case 3:
              this.countyList = []
              this.formInline.county = ''
              this.cityList = res.list;
              break;
            case 4:
              this.countyList = res.list;
              break;
          }
        })
      }
    },
    computed: {

    },
    created() {
      // 初始化获取数据
      this.formInline.time = '昨日'
      let timer = this.timeForMat(1)
      this.formInline.date = [timer.t2, timer.t1]
      this.cityPageList(2)
      userbuildinglist({page: 1, rows: 100}).then(res=>{
        this.buildingIds = []
          if (res && res.list) {
            res.list.map((item)=>{
              this.buildingIds.push(item.buildingId)
            })
            this.initData()
          } else {
            this.initData()
          }
        }).catch(err=>{
          this.$Message.error(err)
        })
    },
    mounted() {
      window.onresize = () => {
        return (() => {
          setTimeout(() => {
            this.onresizeHeight = window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 100
          }, 10);
        })();
      };
    },
    watch: {

    },
  }
</script>
<style lang="scss" scoped>
.ivu-radio-group-button .ivu-radio-wrapper-checked{
    background-color: #2d8cf0 !important;
    color: #fff;
  }
  .personalClueDataStyle{
    padding: 10px 14px;
    .formStyle{
      margin-bottom: 20px;
    }
    .spanMarginRL{
      margin: 0px 6px 0px 30px;
    }
    .spanMargin{
      margin: 0px 6px 0px 0px;
    }
    /* page */
    .pagePublicStyle {
      width: 100%;
      margin: 14px 0;
      height: 32px;
      .totalCount {
        position: absolute;
        height: 32px;
        line-height: 32px;
        display: inline-block;
        vertical-align: top;
        color: #657180;
      }
      .pager {
        display: inline-block;
        vertical-align: top;
        position: absolute;
        right: 20px;
        background-color: #fff;
        padding-left: 50px;
      }
    }
  }
</style>
